package com.tianlh.zookeeper.jute;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;

import lombok.Getter;
import lombok.Setter;
import org.apache.jute.BinaryInputArchive;
import org.apache.jute.BinaryOutputArchive;
import org.apache.jute.InputArchive;
import org.apache.jute.OutputArchive;
import org.apache.jute.Record;
import org.apache.zookeeper.server.ByteBufferInputStream;

/**
 * @author 黑子
 * @Date 2018/1/15 10:50
 */
@Getter
@Setter
public class MocHeader implements Record {

    private long sessionId;
    private String type;

    public MocHeader(){}
    public MocHeader(long sessionId, String type){
        this.sessionId = sessionId;
        this.type = type;
    }

    @Override
    public void serialize(OutputArchive outputArchive, String tag) throws IOException {
        outputArchive.startRecord(this, tag);
        outputArchive.writeLong(sessionId,"sessionId");
        outputArchive.writeString(type, "type");
        outputArchive.endRecord(this, tag);
    }

    @Override
    public void deserialize(InputArchive inputArchive, String tag) throws IOException {
        inputArchive.startRecord(tag);
        sessionId = inputArchive.readLong("sessionId");
        type = inputArchive.readString("type");
        inputArchive.endRecord(tag);
    }

    public static void main(String[] args) throws IOException {

        final String tag = "header";
        // 序列化
        ByteArrayOutputStream baos = new ByteArrayOutputStream() ;
        BinaryOutputArchive boa = BinaryOutputArchive.getArchive(baos);
        new MocHeader(100001L, "MyHeader").serialize(boa, tag);

        // 包装成ByteBuffer 用于网络传输
        ByteBuffer bb = ByteBuffer.wrap(baos.toByteArray());

        // 反序列化
        ByteBufferInputStream bbis = new ByteBufferInputStream(bb);
        BinaryInputArchive bbia = BinaryInputArchive.getArchive(bbis);
        MocHeader header = new MocHeader();
        header.deserialize(bbia, tag);

        baos.close();
        bbis.close();
    }
}
